<template>
  <el-dialog
    title="生产改善任务"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="94%"
    height="88%"
    v-dialog-drag
    class="work-abnormal-dialog"
    :close-on-click-modal="false"
    top="3vh"
    @close="dialogClose()"
    @open="dialogOpen()"
  >
    <div class="box-card">
      <el-form ref="queryForm" :inline="true"  class="clearfix"  @submit.native.prevent>
        <el-form-item>
          <el-cascader
            v-model="erpCommonList"
            :options="treeList"
            :props='defaultProps'
            clearable
            ref="cascader"
            style="width: 360px;"
            size="small"
            readonly
            @change="selectQuery"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item class="more">
          <el-button
            type="primary"
            size="mini"
            @click="handleReport"
            v-hasPermi="['leanTask:report:add']"
            >上报改善点</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['leanTask:center:add']"
            >新增任务</el-button
          >
          <el-link type="warning" :underline="false" @click="lookMore">更多
            <img src="@/assets/images/workbench/arr-right.png"/>
          </el-link>
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="item in tabList"
          :key='item.name'
          :label="item.label"
          :name="item.name"
        >
          <div class="item" slot="label">
            <img :src="item.path">
            <span class="name">{{item.label}}</span>
            <span class="total-fz" :style="{color:item.num ? item.color : '#606266'}">{{item.num}}</span>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-table
        ref="Table"
        :data="tableData"
        :key="activeName"
        tooltip-effect="dark"
        show-overflow-tooltip
        style="width: 100%;overflow: auto;"
        height="calc(100% - 40px - 40px - 40px - 32px)"
        v-loading="loading"
      >
        <el-table-column width="120" v-for="(item,index) in columnData" :key="item.key" :label="item.label" :width='item.width'>
          <span slot-scope="{ row }" v-if='activeName != 3 && item.prop == "taskName"'>
            <el-button type="text" @click.stop="handleLook(row)">{{row.taskName}}</el-button>
          </span>

          <span slot-scope="{ row }" v-else-if='activeName == 3 && item.prop == "reportTaskName"'>
            <el-button type="text" @click.stop="handlePointLook(row)">{{row.reportTaskName}}</el-button>
          </span>

          <span slot-scope="{ row }" v-else-if='activeName == 3 && item.prop == "status"'>
            <span>{{statusMap[row.status]}}</span>
          </span>

          <span slot-scope="{ row }" v-else-if='activeName != 3 && item.prop == "status"'>
            <span>{{taskStatusMap[row.status]}}</span>
          </span>

          <template slot-scope="{ row }" v-else>
            <span>{{row[item.prop]}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="{row}">
            <!-- "1": "待执行","2": "待审核","3": "已完成","4": "已驳回","5": "执行中","9": "已超时" -->
            <template v-if='activeName == 1'>
              <template v-if='(row.status == 1 || row.status == 4 || row.status == 5 || row.status == 9) && row.execUserName === name'>
                <el-button v-hasPermi="['leanTask:center:execute']" type="text" @click="handleExecute(row)">执行</el-button>
                <el-button v-hasPermi="['leanTask:center:transfer']" type="text" @click="handleTransfer(row)">转办</el-button>
              </template>
            </template>

            <template v-if='activeName == 2'>
              <el-button v-hasPermi="['leanTask:center:approval']"  v-if='row.status == 2 && row.createUserName === name' type="text" @click="handleApproval(row)">审核</el-button>
            </template>

            <template v-if='activeName == 3'>
              <el-button v-hasPermi="['leanTask:report:approval']" v-if='row.status == 1 && row.checkUserName === name' type="text" @click="approvalReport(row)">审核</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if='pager.total > 10'
        :total="pager.total"
        :page.sync="pager.pageNum"
        :limit.sync="pager.pageSize"
        @pagination="getData"
      />

      <point-report-dialog
        :visible.sync="reportDialog.visible"
        :row="reportDialog.row"
        @submit-success="updateData"
      />

      <point-approval-dialog
        :visible.sync="approvalReportDialog.visible"
        :row="approvalReportDialog.row"
        @submit-success="updateList"
      />

      <task-execute-dialog
        :visible.sync="executeDialog.visible"
        :row="executeDialog.row"
        @submit-success="updateList"
      />

      <transfer-dialog
        :visible.sync="transferDialog.visible"
        :row="transferDialog.row"
        @submit-success="updateList"
      />
      <task-approval-dialog
        :visible.sync="approvalDialog.visible"
        :row="approvalDialog.row"
        @submit-success="updateList"
      />

      <task-add-dialog
        :visible.sync="addDialog.visible"
        :row="addDialog.row"
        @submit-success="updateData"
      />

      <!-- 任务详情 -->
      <task-detail-dialog
        :visible.sync="lookDialog.visible"
        :row="lookDialog.row"
        :mode="lookDialog.mode"
      />
      <!-- 改善点详情 -->
      <point-detail-dialog
        :visible.sync="pointLookDialog.visible"
        :row="pointLookDialog.row"
      />
    </div>
  </el-dialog>
</template>
<script>
  import pointReportDialog from "@/views/leanTask/components/pointReportDialog";
  import pointApprovalDialog from "@/views/leanTask/components/pointApprovalDialog";
  import pointDetailDialog from "@/views/leanTask/components/pointDetailDialog";
  import taskExecuteDialog from "@/views/leanTask/components/taskExecuteDialog";
  import taskAddDialog from "@/views/leanTask/components/taskAddDialog";
  import transferDialog from "@/views/leanTask/components/transferDialog";
  import taskApprovalDialog from "@/views/leanTask/components/taskApprovalDialog";
  import taskDetailDialog from "@/views/leanTask/components/taskDetailDialog";
  import {workHandleList,workApprovalList,workOutList,workReportList} from "@/api/workbench/index";
  import {taskStatusMap,statusMap } from "@/views/leanTask/enum";
  import { mapState,mapActions,mapGetters} from "vuex";
export default {
  props:{
    tabName:{
      type:String,
      default:"1"
    },
    visible: {
      type: Boolean,
      default: false
    },
    imporveTotal:{
      type: Array,
      default: [0,0,0,0]
    }
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    ...mapGetters([
      'treePermitList',
      'name'
    ]),
  },

  data() {
    return {
      tabList:[
        {label:"待处理",name:"1",path:require("@/assets/images/workbench/todo.png"),num:0,color:"#FF9300"},
        {label:"待审核任务",name:"2",path:require("@/assets/images/workbench/doing.png"),num:0,color:"#2F83FF"},
        {label:"待审核上报 ",name:"3",path:require("@/assets/images/workbench/approval.png"),num:0,color:"#FF9300"},
        {label:"已超时 ",name:"4",path:require("@/assets/images/workbench/warning.png"),num:0,color:"#F54E1E"}
      ],
      columnData:[],
      otherColumn:[
        {label:"名称",prop:"taskName",key:1},
        {label:"车间",prop:"workshopName",key:2},
        {label:"产线",prop:"lineName",key:3},
        {label:"状态",prop:"status",key:4,},
        {label:"任务截止时间",prop:"execEndDate",key:5,width:165}
      ],
      approvalColumn:[
        {label:"名称",prop:"reportTaskName",key:1},
        {label:"车间",prop:"workshopName",key:2},
        {label:"产线",prop:"lineName",key:3},
        {label:"上报人",prop:"reportName",key:4},
        {label:"状态",prop:"status",key:5},
        {label:"上报时间",prop:"reportDate",key:6,width:165}
      ],
      tableData:[],
      loading: false,
      activeName:"1",
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      columnMap:{
        "1":"otherColumn",
        "2":"otherColumn",
        "3":"approvalColumn",
        "4":"otherColumn"
      },
      //改善任务列表-待处理
      // 改善任务列表-待审核
      // 待审核上报改善点
      // 改善任务列表-今日超时
      functionMap:{
        "1":workHandleList,
        "2":workApprovalList,
        "3":workReportList,
        "4":workOutList
      },
      reportDialog: {
        visible: false,
        row: null,
      },
      approvalReportDialog:{
        visible: false,
        row: null
      },
      executeDialog: {
        visible: false,
        row: null,
      },
      transferDialog: {
        visible: false,
        row: null,
      },
      approvalDialog: {
        visible: false,
        row: null,
      },
      addDialog: {
        visible: false,
      },
      lookDialog:{
        visible: false,
        row: null,
        mode:null
      },
      pointLookDialog:{
        visible: false,
        row: null
      },
      efaultProps: {
        value: "code",
        label: "label",
        checkStrictly: true,
        emitPath: true,
      },
      queryParmas:{
        factoryDeptId:null,
        workshopId: null,
        lineId:null
      },
      erpCommonList:[],
      treeList:[],
      taskStatusMap,
      defaultProps: {
        value: "code",
        label: "label",
        checkStrictly: true,
        emitPath: true,
      },
      dialogType:"",
      statusMap
    };
  },

  methods:{
    dialogClose(){
      this.resetFormData()
    },

    dialogOpen(){
      if(this.imporveTotal?.length){
        this.imporveTotal.forEach((item,index) => {
          this.tabList[index].num = item
        })
      }
      this.activeName = this.tabName ? this.tabName : "1";
      this.columnData = this[this.columnMap[this.activeName]];
      this.treeList = this.treePermitList.map(factory => {
        return{
          code:factory.code,
          id:factory.id,
          label:factory.label,
          children:factory?.children?.length ? factory.children.map(workshop => {
            return{
              code:workshop.code,
              id:workshop.id,
              label:workshop.label,
              workshopType:workshop.workshopType,
              children:workshop?.children?.length ? workshop.children.map(line => {
                return{
                  code:line.code,
                  id:line.id,
                  label:line.label
                }
              }):[]
            }
          }):[]
        }
      })
      this.treeList = this.getTreeData(this.treeList);
      this.getData()
    },

    getList(funName){
      this.loading = true;
      const { pageNum, pageSize } = this.pager;
      const param = {
        query:this.queryParmas,
        pageNum,
        pageSize,
      };
      funName(param)
      .then((res) => {
        if(res.code == 200){
          this.tableData = res?.rows || [];
          this.pager.total = res?.total || 0;
          if(funName == this.functionMap["1"]){
            this.tabList[0].num = res?.total || 0;
          }
          else if(funName == this.functionMap["2"]){
            this.tabList[1].num = res?.total || 0;
          }
          else if(funName == this.functionMap["3"]){
            this.tabList[2].num = res?.total || 0;
          }
          else if(funName == this.functionMap["4"]){
            this.tabList[3].num =res?.total || 0;
          }
          this.loading = false;
        }else{
          this.tableData = [];
          this.pager.total = 0;
          this.pager.pageNum = 1;
          this.loading = false;
        }
      })
      .catch(() => {
        this.tableData = [];
        this.pager.total = 0;
        this.pager.pageNum = 1;
        this.loading = false;
      });
    },

    getData(){
      const funName = this.functionMap[this.activeName];
      this.getList(funName);
    },

    updateList(){
      this.getData()
      this.$emit("updateTotal",this.activeName)
    },

    updateData(){
      if(this.dialogType == "point"){//上报改善点
        this.activeName = "3";
      }
      else if(this.dialogType == "task"){//新增任务
        this.activeName = "1";
      }
      this.columnData = [];
      this.tableData = [];
      this.pager.total = 0;
      this.pager.pageNum = 1;
      this.columnData = this[this.columnMap[this.activeName]];
      this.updateList()
    },

    //上报改善点
    handleReport() {
      this.reportDialog.row = null;
      this.reportDialog.visible = true;
      this.dialogType = "point"
    },

    // 审核上报改善点
    approvalReport(row){
      this.approvalReportDialog.row = row;
      this.approvalReportDialog.visible = true;
    },

    //执行任务
    handleExecute(row){
      this.executeDialog.row = row;
      this.executeDialog.visible = true;
    },

    //转办任务
    handleTransfer(row) {
      this.transferDialog.row = row;
      this.transferDialog.visible = true;
    },

    //审核任务
    handleApproval(row){
      this.approvalDialog.row = row;
      this.approvalDialog.visible = true;
    },

    //新增任务
    handleAdd(){
      this.addDialog.visible = true;
      this.dialogType = "task"
    },

    //查看任务详情
    handleLook(row){
      this.lookDialog.row = row;
      this.lookDialog.mode = "task";
      this.lookDialog.visible = true;
    },

    //查看改善点详情
    handlePointLook(row){
      this.pointLookDialog.row = row;
      this.pointLookDialog.visible = true;
    },

    handleClick(tab, event) {
      this.loading = true;
      this.columnData = [];
      this.tableData = [];
      this.pager.total = 0;
      this.pager.pageNum = 1;
      this.activeName = tab.name;
      this.columnData = this[this.columnMap[this.activeName]];
      this.loading = false;
      this.getData()
    },

    lookMore(){
      this.$router.push({ path: "../leanTask/center"}).catch(()=>{});
    },
    selectQuery(list){
      const item = this.$refs["cascader"].getCheckedNodes();
      console.log(item,"itemitem")
      if(item?.length){
       if(item[0].level == 3){//选产线
          this.queryParmas = {
            factoryDeptId:item[0]?.pathNodes[0]?.data?.id || null,
            workshopId:item[0]?.pathNodes[1]?.data?.id || null,
            lineId:item[0]?.data?.id || null
          }
        }
        else if(item[0].level == 2){//选车间
          this.queryParmas = {
            factoryDeptId:item[0]?.pathNodes[0]?.data?.id || null,
            workshopId:item[0]?.pathNodes[1]?.data?.id || null,
            lineId:null
          }
        }
        else if(item[0].level == 1){//选工厂
          this.queryParmas = {
            factoryDeptId:item[0]?.pathNodes[0]?.data?.id || null,
            workshopId:null,
            lineId:null
          }
        }
      }else{
        this.queryParmas = {
          factoryDeptId:null,
          workshopId: null,
          lineId:null
        }
      }
      this.getData()
    },
    resetFormData(){
      this.columnData = [];
      this.tableData = [];
      this.activeName = "1";
      this.erpCommonList = [];
      this.queryParmas = {
        factoryDeptId:null,
        workshopId: null,
        lineId:null
      }
    }
  },
  updated() {
    if (this.$refs.Table && this.$refs.Table.doLayout) {
      this.$refs.Table.doLayout();
    }
  },
  components:{
    pointReportDialog,
    pointApprovalDialog,
    pointDetailDialog,
    taskExecuteDialog,
    taskAddDialog,
    transferDialog,
    taskApprovalDialog,
    taskDetailDialog
  }
};
</script>
<style lang="scss" scoped>
  .work-abnormal-dialog{
    ::v-deep.el-dialog__body{
      height:calc(100vh - 12rem);
      max-height:calc(100vh - 12rem);
      padding:8px 16px 0 16px;
      .box-card{
        width: 100%;
        height:100%;
        .clearfix{
          color: #F59A23;
          .block-title{
            margin-bottom: 0;
            flex:1
          }
          .block-title{
            margin-bottom: 0;
            .title.line{
              color: #313131;
            }
            .title::before{
              background:#34855B;
            }
          }
          .more{
            margin-bottom: 0.5rem;
            font-size:14px;
            .el-link.el-link--warning{
              margin-left: 10px;
              margin-top: 2px;;
              color:#34855B;
              .el-link--inner{
                display:flex;
                align-items: center;
              }
              img{
                width: 16px;
                height: 16px;
              }
            }
          }
        }
        .el-tabs{
          display: flex;
          align-items: center;
          justify-content: space-between;
          .item {
            display: flex;
            align-items: center;
            img{
              width: 18px;
              height: 18px;
            }
            .name{
              padding:0 6px
            }
            .total-fz{
              font-size:16px;
              line-height: 16px;
            }
          }
          .el-tabs__content{
            margin: 0 0 0.9375rem;
          }
        }
        .pagination-container{
          margin-top: 0;
          margin-bottom: 0;
        }
      }
    }
  }
</style>
